package com.mf.controller;

import com.mf.entity.po.User;
import com.mf.enums.Gender;
import com.mf.result.Result;
import com.mf.service.IUserService;
import com.mf.utils.EnumUtils;
import com.mf.utils.RegularVerificationUtils;
import com.mf.utils.VerifyIsErrorUtils;
import com.mf.utils.VerifyUtils;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import jakarta.validation.Valid;
import org.n3r.idworker.Sid;
import org.springframework.web.bind.annotation.*;


/**
 * 用户表
 *
 * @author mf
 * @since 2024-07-05
 */
@RestController
@RequestMapping("/user")
@Tag(name = "用户表")
public class UserController {
    @Resource
    private IUserService userService;

    @Operation(summary = "新增")
    @PostMapping("add")
    public Result<String> add(@RequestBody @Valid User user) {
        if(VerifyUtils.isEmpty(user.getGender())){
            user.setGender(Gender.UNKNOWN.value);
        }

        if(!EnumUtils.existsInEnum(Gender.class, user.getGender(), "value")){
            return Result.fail("性别类型不存在");
        }

        if(VerifyUtils.isNotEmpty(user.getPhone()) && !RegularVerificationUtils.validatePhoneNumber(user.getPhone())){
            return Result.fail("手机号格式不正确");
        }

        if(VerifyUtils.isNotEmpty(user.getEmail()) && !RegularVerificationUtils.validateEmail(user.getEmail())){
            return Result.fail("邮箱格式不正确");
        }

        if(userService.getUserByUserName(user.getUserName()) > 0){
            return Result.fail("账号已存在");
        }

        // 密码盐
        user.setPasswordSale(Sid.nextShort());

        userService.save(user);
        return Result.success(null);
    }

    @Operation(summary = "编辑")
    @PostMapping("edit")
    public Result<String> edit(@RequestBody User user) {
        VerifyIsErrorUtils.isEmpty(user.getId(), "id不能为空");
        userService.edit(user);
        return Result.success(null);
    }

    @Operation(summary = "删除")
    @GetMapping("delete")
    public Result<String> delete(@RequestParam("id") Integer id) {
        VerifyIsErrorUtils.isEmpty(id, "id不能为空");
        userService.removeById(id);
        return Result.success(null);
    }

    @Operation(summary = "根据id查询")
    @GetMapping("getById")
    public Result<User> getById(@RequestParam("id") Integer id) {
        VerifyIsErrorUtils.isEmpty(id, "id不能为空");
        return Result.success(userService.getById(id));
    }

    @Operation(summary = "修改账户状态")
    @GetMapping("updateStatus")
    public Result<String> updateStatus(@RequestParam("id") Integer id, @RequestParam("status") Integer status) {
        userService.updateStatus(id, status);
        return Result.success(null);
    }
}
